<template>
  <div class="red-box"></div>
  <div class="wrap">
    <img class="title-img" src="@/assets/home/shishiyali@2x.png" />
    <div class="list-box-wrap">
      <div class="list-box">
        <template v-for="(item, index) in homeStore.implementPressureDataObj" :key="item.title">
          <div class="item color_1" v-if="key1.includes(index+1)"> 
            <div class="title">{{item.title}}</div>
            <div class="number">{{item.value}}</div>
            <div class="mpa">Mpa</div>
            <div class="chart-wrap">
              <div class="inner-wrap" :id="`char${index+1}-inner-wrap`">
                <canvas :id="`char${index+1}`" class="chart" width="110" height="110"></canvas>
                <div class="cir-smark" :id="`chart-mark${index+1}`"><img src="@/assets/home/mark-1.png" /></div>
              </div>
            </div>
            <div class="cir-line"></div>
          </div>

          <div class="item color_2" v-if="key2.includes(index+1)">
            <div class="title">{{item.title}}</div>
            <div class="number">{{item.value}}</div>
            <div class="mpa">Mpa</div>
            <div class="chart-wrap" :id="`char${index+1}-inner-wrap`">
              <div class="inner-wrap">
                <canvas :id="`char${index+1}`" class="chart" width="110" height="110"></canvas>
                <div class="cir-smark" :id="`chart-mark${index+1}`"><img src="@/assets/home/mark-2.png" /></div>
              </div>
            </div>
            <div class="cir-line"></div>
          </div>

          <div class="item color_3" v-if="key3.includes(index+1)">
            <div class="title">{{item.title}}</div>
            <div class="number">{{item.value}}</div>
            <div class="mpa">Mpa</div>
            <div class="chart-wrap">
              <div class="inner-wrap" :id="`char${index+1}-inner-wrap`">
                <canvas :id="`char${index+1}`" class="chart" width="110" height="110"></canvas>
                <div class="cir-smark" :id="`chart-mark${index+1}`"><img src="@/assets/home/mark-3.png" /></div>
              </div>
            </div>
            <div class="cir-line"></div>
          </div>
        </template>
        

      </div>
    </div>

  </div>
</template>

<script setup>
import { useHomeStore } from '@/Store/homeStore';
import { onMounted, nextTick } from 'vue';
import CirBiaoJi from '@/assets/home/cir-biaoji.png';


const homeStore = useHomeStore();
const key1 = [1,4,7,10,13,16,19];
const key2 = [2,5,8,11,14,17,20];
const key3 = [3,6,9,12,15,18,21];


function drawAnnotatedRingChart(ctx, value, totalValue, backgroundColors, gradientColors, markerImage) {
      const centerX = ctx.canvas.width / 2;
      const centerY = ctx.canvas.height / 2;
      const radius = 49;

      // 绘制背景圆环
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      ctx.strokeStyle = backgroundColors[0];
      ctx.lineWidth = 0;
      ctx.stroke();

      // 创建渐变色
      const gradient = ctx.createLinearGradient(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
      for (let i = 0; i < gradientColors.length; i++) {
        const colorStop = i / (gradientColors.length - 1);
        gradient.addColorStop(colorStop, gradientColors[i]);
      }

      // 绘制进度圆环
      const progressAngle = (2 * Math.PI * value / totalValue);
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, progressAngle);
      ctx.lineWidth = 8;
      ctx.strokeStyle = gradient;
      ctx.stroke();

      // 计算标记图片的位置（假设缺口在正上方，即角度为 Math.PI/2）
      const markerAngle = progressAngle + Math.PI / 2;
      const markerX = centerX + Math.sin(markerAngle) * radius;
      const markerY = centerY - Math.cos(markerAngle) * radius;

      // 保存当前绘图状态
      ctx.save();

      // 移动到标记位置并旋转以使其垂直于进度切面且再旋转 90°
      ctx.translate(markerX, markerY);
      ctx.rotate(markerAngle - Math.PI / 2 + Math.PI / 2);

      // 设置图片缩放倍率，这里假设缩小为原来的 0.2 倍（可按需调整）
      const scaleFactor = 0.4;
      const scaledWidth = markerImage.width * scaleFactor;
      const scaledHeight = markerImage.height * scaleFactor;

      // 绘制标记图片，确保图片在进度条边界
      ctx.drawImage(markerImage, -scaledWidth / 2, -scaledHeight / 2, scaledWidth, scaledHeight);
      
      
      // 保存当前绘图状态
      ctx.save();
      return {
        markerX,
        markerY,
      }
}


function rotateDivTowardsPoint(markerX, markerY, markDomId, targetWrapDom, num) {
    // 箭头指标正方形框
    const smallSquare = document.getElementById(markDomId);
    // 画布容器
    const targetPoint = document.getElementById(targetWrapDom);
    // 获取容器的位置
    const targetRect = targetPoint.getBoundingClientRect();
    // 获取目标点真实坐标
    const targetX = targetRect.x + markerX;
    const targetY = targetRect.y + markerY;

    // 获取小正方形相对于容器的实际位置
    const smallSquareRect = smallSquare.getBoundingClientRect();
    const smallSquareCenterX = smallSquareRect.left + smallSquareRect.width / 2;
    const smallSquareCenterY = smallSquareRect.top + smallSquareRect.height / 2;
    // 计算旋转角度
    function calculateRotation() {
      const deltaX = targetX - smallSquareCenterX; // 小正方形中心点与目标点的X轴距离
      const deltaY = targetY - smallSquareCenterY; // 小正方形中心点与目标点的Y轴距离
      let angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI); // 弧度转角度

      // 偏差修正
      if(num < 0.3 && num >= 0.0){
        angle = angle + 80;
      } else if( num >= 0.3) {
        angle = angle + 90;
      } 
      return angle;
    }

    // 更新小正方形的旋转角度
    function updateRotation() {
      const angle = calculateRotation();
      smallSquare.style.transform = `rotate(${angle}deg)`;
    }

    // 调用函数初始化旋转
    updateRotation();
}

const initChar = (id, num, markDom, targetWrapDom) => {
  const canvas = document.getElementById(id);
  const ctx = canvas.getContext('2d');
  const valueFromImage = num > 1 ? 0.0 : num;
  const totalValue = 1;
  const backgroundColors = ['#FFFFFF00'];
  let gradientColors = ['#1dd5d1','#1dd5d160','#1dd5d130'];
  const str = Number(id.replace('char',''));
  console.log(str)
  if(id === 'char2') {
    gradientColors = ['#eabb14', '#eabb1460', '#eabb1430'];
  }
  if(id === 'char3') {
    gradientColors = ['#20bacf','#20bacf60','#20bacf30']; 
  }
  const markerImage = new Image();
  markerImage.src = CirBiaoJi;
  markerImage.onload = function () {
    const {markerX, markerY} = drawAnnotatedRingChart(ctx, valueFromImage, totalValue, backgroundColors, gradientColors, markerImage);
    rotateDivTowardsPoint(markerX - 8, markerY - 9, markDom, targetWrapDom, valueFromImage);
  };


}

onMounted(() => {
  setTimeout(() => {
    homeStore.implementPressureDataObj.forEach((item, index) => {
      initChar(`char${index+1}`, item.value, `chart-mark${index+1}`, `char${index+1}`);
    })
  }, 500)
})

</script>

<style lang="scss" scoped>
.wrap {
  width: 100%;
  background: linear-gradient(90deg, rgba(33, 100, 156, 0.5) 0%, rgba(29, 70, 143, 0.25) 100%);
  border: 1px solid rgba(35, 135, 217, 1);
  overflow: hidden;
  border-radius: 11px;
  margin-top: 8px;
  .title-img {
    width: 178px;
    height: 34px;
    margin: 11px auto 10px 42px;
  }
  .list-box-wrap {
    width: 476px;
    margin-left: 60px;
    margin-bottom: 21px;
    display: flex;
    justify-content: flex-start;
    overflow-x: auto;
  }
  .list-box{
    display: flex;
    justify-content: flex-start;
    .item {
      position: relative;
      width: 125px;
      height: 172px;
      opacity: 1;
      border-radius: 16px;
      background: linear-gradient(180deg, rgba(0, 186, 173, 0.52) 0%, rgba(20, 38, 56, 0) 100%);
      margin: 0px 10px;
      .title {
        font-size: 16px;
        font-weight: 700;
        letter-spacing: 0px;
        line-height: 21.22px;
        color: rgba(255, 255, 255, 1);
        vertical-align: top;
        text-align: center;
        margin-top: 12px;
      }
      .chart-wrap {
        position: absolute;
        left: 10px;
        top: 43px;
        width: 100px;
        height: 100px;
        .inner-wrap{
          position: relative;
        }
      }
      .chart {
        width: 100px;
        height: 100px;
        background: url("@/assets/home/shishi_bg.png") no-repeat left top;
        background-size: 98% 98%;
      }
      .cir-line{
        position: absolute;
        left: 50%;
        margin-left: -39.5px;
        top: 50%;
        margin-top: -30px;
        width: 75px;
        height: 75px;
        border: 2px solid transparent;
        background: url("@/assets/home/shishi_bg_cir.png") no-repeat center center;
        background-size: 100% 100%;
      }
      .cir-smark{
        width: 10px;
        height: 10px;
        position: absolute;
        left: 50%;
        margin-left: -5px;
        bottom: 23px;
        z-index: 0;
        &::before {
          position: absolute;
          content: ' ';
          display: block;
          width: 6px;
          height: 6px;
          background: #FFF;
          border-radius: 50%;
          z-index: 150;
          left: 50%;
          margin-left: -3px;
          bottom: 2px;
        }
        img {
          position: absolute;
          z-index: 0;
          left: 0;
          bottom: 0;
          width: 100%;
          height: auto;
        }
      }
      .number {
        position: absolute;
        width: 100%;
        text-align: center;
        top: 67px;
        text-shadow: 0px 0px 6px  rgba(40, 227, 228, 1);
        /** 文本1 */
        font-size: 25px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 36.2px;
        color: rgba(255, 255, 255, 1);
      }
      .mpa {
        position: absolute; 
        text-shadow: 0px 0px 6px  rgba(40, 227, 228, 1);
        /** 文本1 */
        font-size: 20px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 28.96px;
        color: rgba(255, 255, 255, 1);
        text-align: right;
        bottom: 3px;
        width: 100%;
        text-align: center;
      }
    }
  }
}

.list-box {
  .color_2 {
    background: linear-gradient(180deg, rgba(255, 141, 26, 0.52) 0%, rgba(20, 38, 56, 0) 100%) !important;
    .chart {
      background: url("@/assets/home/shishi_bg.png") no-repeat left top !important;
      background-size: 100% 100% !important;
    }
  }
  .color_3 {
    background: linear-gradient(180deg, rgba(42, 130, 228, 0.52) 0%, rgba(20, 38, 56, 0) 100%) !important;
    .chart {
      background: url("@/assets/home/shishi_bg.png") no-repeat left top !important;
      background-size: 100% 100% !important;
    }
  }
}

.red-box{
  position: absolute;
  border-radius: 50%;
  width: 2px;
  height: 2px;
  z-index: 1000;
  background: red;
}

</style>